//
//  ProcessManage.swift
//  frptool
//
//  Created by 傅攀 on 2019/11/20.
//  Copyright © 2019 傅攀. All rights reserved.
//

import Foundation
import Cocoa
class FRPCProcessManager{
    
   
    
    var process: Process? = nil
    
    var console: MyConsole? = nil
    
    let clientPath: String
    let configPath: String
    
    init(clientPath: String, configPath: String){
        self.clientPath = clientPath
        self.configPath = configPath
    }

    func connect(){
        
        if process != nil {
            process?.terminate()
            process = nil
        }
        
        let delegate = NSApplication.shared.delegate as? AppDelegate
        delegate?.activeStatusBarIcon()
        
        
        DispatchQueue.global().async {
            self.process = Process()
            let pipe = Pipe()
            
           
            
                 
            let outHandle = pipe.fileHandleForReading
            outHandle.waitForDataInBackgroundAndNotify()
            
            NotificationCenter.default.addObserver(forName: NSNotification.Name.NSFileHandleDataAvailable, object: outHandle, queue: nil){
                     notification -> Void in
                     let data = outHandle.availableData
                     
                     if data.count > 0 {
                         if let str = String(data:data,encoding: String.Encoding.utf8) {
                             
                             DispatchQueue.main.async {
                                 self.console?.log(text:str )
                             }
                         }
                     }
                     
            }
            
            let pipe2 = Pipe()
            let outHandle2 = pipe2.fileHandleForReading
            
            outHandle2.waitForDataInBackgroundAndNotify()
            
            NotificationCenter.default.addObserver(forName: NSNotification.Name.NSFileHandleDataAvailable, object: outHandle2, queue: nil) { notification -> Void in
                let data = outHandle2.availableData
                if data.count > 0 {
                    if let str = NSString(data: data,encoding: String.Encoding.utf8.rawValue) {
                        DispatchQueue.main.async {
                            self.console?.error(text: str as String)
                        }
                    }
                }
            }
            
       
                 
            var obs2 : NSObjectProtocol!
            obs2 = NotificationCenter.default.addObserver(forName: Process.didTerminateNotification, object: self.process, queue: nil) { notification -> Void in
                     DispatchQueue.main.async{
                        
                         self.process = nil
                         self.console?.log(text: "process terminated")
                     }
                     NotificationCenter.default.removeObserver(obs2!)
            }
                 
                 
        
            self.process?.launchPath = self.clientPath
            self.process?.arguments = ["-c",self.configPath]
            self.process?.standardOutput = pipe
            self.process?.standardError = pipe2
            self.process?.launch()
                 
                 
            //self.console?.log(text: "process launch")
            self.process?.waitUntilExit()
                 
                 
        }
        
        
    }
    
    
    func disconnect(){
        if process != nil {
            process?.terminate()
            process = nil
        }
        
        let delegate = NSApplication.shared.delegate as? AppDelegate
        delegate?.inactiveStatusBarIcon()
       
        
    }
    
    func disconnectAll(){
        
      
       
        
        
    }
    
    
    
    
}
